#ifndef __M_UTIL_H__
#define __M_UTIL_H__

// 常见功能类,实现一下功能
// 获取系统时间
// 检查文件存在
// 创建目录
// 获取路径

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

namespace Alpaca
{
    namespace util
    {
        class Date
        {
        public:
            static time_t now()
            {
                return time(nullptr);
            }
        };

        class File
        {
        public:
            static bool exists(const std::string &pathname)
            {
                // 多操作系统共用
                struct stat st;
                if (stat(pathname.c_str(), &st) < 0)
                    return false;

                return true;

                // Linux专用
                // return access(pathname.c_str(), F_OK) == 0;
            }

            static std::string path(const std::string &pathname)
            {
                size_t pos = pathname.find_last_of("/\\");
                if (pos == std::string::npos)
                    return ".";
                return pathname.substr(0, pos + 1);
            }

            static void create_directory(const std::string &pathname)
            {
                if(pathname.empty())
                    return;
                if (exists(pathname))
                    return ;
                size_t pos = 0, idx = 0;
                while (idx < pathname.size())
                {
                    pos = pathname.find_first_of("/\\", idx);
                    if (pos == std::string::npos)
                    {
                        mkdir(pathname.c_str(), 0755);
                        return;
                    }
                    if(pos == idx)
                    {
                        idx = pos + 1;
                        continue;
                    }

                    std::string parent_dir = pathname.substr(0, pos + 1);
                    if (parent_dir == "." || parent_dir == "..")
                    {
                        idx = pos + 1; 
                        continue;
                    }

                    if (exists(parent_dir))
                    {
                        idx = pos + 1;
                        continue;
                    }
                    mkdir(pathname.c_str(), 0755);
                    idx = pos + 1;
                }
            }
        };
    }
}

#endif